var map;
var wsUri;
var bounds;

var offenderList = [];

<<<<<<< HEAD
// store offender traces
var tracerContainer = (function() {
=======
var tracerContainer = (function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    var oList = [];

    var instance = {};

    instance.createNew = function (traced) {
        //console.log(traced);
        oList.push(traced);
    };

    instance.getOffender = function (index) {
        return oList[index];
    };

    instance.getLength = function () {
        //console.log(oList.length);
        return oList.length;
    };

    return instance;
})();

<<<<<<< HEAD
// store alerts
var alertList = (function() {
=======
var alertList = (function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    var aList = [];
    var alertNumber = 1;
    var topAlert = 0;
    var instance = {};

    instance.createNew = function (alert) {
        //console.log(alert);
        aList[alertNumber] = alert;
        alertNumber++;
    };

    instance.getAlert = function (index) {
        return aList[index];
    };

    instance.getNumber = function(index) {
        //console.log('Alert Number...');
        //console.log(alertNumber);
        return alertNumber;
    }

    instance.setTopAlert = function(alertNumber) {
        topAlert = alertNumber;
    }

    instance.getTopAlert = function() {
        return topAlert;
    }

    return instance;
})();

<<<<<<< HEAD
// store areas
var areaList = (function() {
=======
var areaList = (function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    var aList = [];

    var instance = {};

    instance.createNew = function (area, oid) {
        aList[area.UID] = new Array();
        aList[area.UID][1] = area;
        aList[area.UID][0] = oid;
    };

    instance.getArea = function (areaUID) {
        return aList[areaUID];
    }

    return instance;
})();

<<<<<<< HEAD
// store makers
var markerList = (function() {
=======
var markerList = (function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    var markers = [];
    var bounds;
    var instance = {};

<<<<<<< HEAD
    instance.add = function(marker, oid) {

        if(markers[oid] == undefined) {
            markers[oid] = marker;            
=======
    instance.add = function (marker, oid) {
        console.log('markerList.add ' + markers[oid]);

        if (markers[oid] == undefined) {
            //console.log('markerList.add added');
            markers[oid] = marker;
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
        } else {
            this.updateMarker(marker, oid);
        }
    };

<<<<<<< HEAD
    instance.updateMarker = function(marker, oid) {     
        markers[oid] = marker;        
=======
    instance.updateMarker = function (marker, oid) {
        console.log('markerList.updateMarker');
        markers[oid] = marker;
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    }

    instance.initializeBounds = function () {
        bounds = new google.maps.LatLngBounds();
    }

<<<<<<< HEAD
    instance.getMarker = function(oid) {
=======
    instance.getMarker = function (oid) {
        console.log('markerList.getMarker ' + markers[oid]);
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea

        if(markers[oid] != undefined) {
            return markers[oid];
        } else {
            return undefined;
        }
    }

<<<<<<< HEAD
    // update the current bounds for all locations
    instance.updateBounds = function(latlng) {
        bounds.extend(latlng);
    }

    // get the current global bounds
    instance.getBounds = function() {
=======
    instance.updateBounds = function (latlng) {
        bounds.extend(latlng);
    }

    instance.getBounds = function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
        return bounds;
    }

    return instance;
})();

$(document).ready(init);

function init() {
<<<<<<< HEAD
    wsUri = 'ws://50.135.224.19:13001/websession';
=======
    wsUri = 'ws://192.168.1.199:13001/websession'/*'ws://50.225.134.19/signalr'*/;
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(47.609722, -122.333056),
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('google-maps'), mapOptions);
    bounds = new google.maps.LatLngBounds();
    var testlatlng = new google.maps.LatLng(47.454138, -122.267189);
    bounds.extend(testlatlng);

<<<<<<< HEAD
    /*setTimeout(function() {
=======
    //parseResponseLocations(testJSON());
    //parseAlerts(testAlert());

    console.log('Tracer Length:' + tracerContainer.getLength());

    setTimeout(function () {
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
        initTest();
    }, 2000);*/
    //$('#alert-0'/*'#' + alertNum + ' .OID'*/).css('visibility', 'visible');
}

<<<<<<< HEAD
$(window).load( function() {
    connection();
=======
$(window).load(function () {
    connection();
    //signalRconnection();
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
});

function onMessageHandler(message) {
    var data = jQuery.parseJSON(message);
<<<<<<< HEAD

    if(data.Offenders != undefined) {
=======
    console.log(data);

    if (data.Offenders != undefined) {
        console.log('Offender message...');
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
        parseResponseLocations(data);
    } else if (data.Alerts != undefined) {
        parseAlerts(data);
    } else if (data.Areas != undefined) {
        parseAreas(data);
    } else if (data.Locations != undefined) {
        parseLocations(data);
    }

}

// message parsers
//
//
function parseResponseLocations(response) {
    var data = response;
<<<<<<< HEAD

    for(var i = 0; i < data.Offenders.length; i++) {
        var offenderContainer = {
            'OID' : data.Offenders[i].Offender[0].OID,
            'latitude' : data.Offenders[i].Offender[i].Location[0].Lat,
            'longitude' : data.Offenders[i].Offender[i].Location[0].Lon,
            'timestamp' : data.Offenders[i].Offender[i].Location[0].TimeStamp
        };

        tracerContainer.createNew(offenderContainer);
        setUserLocation(offenderContainer.OID, offenderContainer.latitude, offenderContainer.longitude);        
=======
    console.log('Array Length: ' + data.Offenders.length);
    for (var i = 0; i < data.Offenders.length; i++) {
        var offenderContainer = {
            'OID': data.Offenders[i].Offender[0].OID,
            'latitude': data.Offenders[i].Offender[1].Locations[0].Lat,
            'longitude': data.Offenders[i].Offender[1].Locations[0].Long,
            'timestamp': data.Offenders[i].Offender[1].Locations[0].TimeStamp
        };

        tracerContainer.createNew(offenderContainer);
        setUserLocation(offenderContainer.OID, offenderContainer.latitude, offenderContainer.longitude);
        //console.log(tracerContainer.getOffender(i));
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    }


}

function parseAlerts(response) {
    var oidString = '';
    var data = response;
<<<<<<< HEAD
    var alertNum;

    var topAlertTotal = 0;
    var newAlertTotal = 1;

    for(var i = 0; i < data.Alerts.length; i++) {
        var alertNum = alertList.getNumber();

        alertList.createNew(data.Alerts[i]);

        var cloned = $('#alert-' + alertList.getTopAlert()).clone();
        cloned.attr('id', 'alert-' + alertNum);

        console.log('Placing alert: ' + alertNum + ' above #alert-' + alertList.getTopAlert());
        cloned.insertBefore('#alert-' + alertList.getTopAlert());
        
        // remove template alert
        $('#alert-0').remove();        
        alertList.setTopAlert(alertNum);
        $('#alert-' + alertNum + ' .timestamp').text(data.Alerts[i].TimeStamp);  
        $('#alert-' + alertNum + ' .alert-title').text(data.Alerts[i].AlertTitle); 

        if(data.Alerts[i].Location == -1) {
            $('#alert-' + alertNum + ' .alert-location').text('');           
        } else {
            $('#alert-' + alertNum + ' .alert-location').text(areaList.getArea(data.Alerts[i].Location)[1].Name);           
        }
        $('#alert-' + alertNum + ' .alert-event').text(data.Alerts[i].Message);

        for(var y = 0; y < data.Alerts[i].OIDs.length; y++) {
            var mapslatlng = new google.maps.LatLng(data.Alerts[i].OIDs[y].Lat, data.Alerts[i].OIDs[y].Lon);
=======
    for (var i = 0; i < data.Alerts.length; i++) {
        alertList.createNew(data.Alerts[i]);
        //console.log(data.Alerts[i]);
        var cloned = $('#init-alert').clone();
        cloned.attr('id', data.Alerts[i].Number);

        //console.log('TimeStamp: ' + data.Alerts[i].TimeStamp);
        cloned.insertBefore("#init-alert");
        $('#' + data.Alerts[i].Number + ' .timestamp').text(data.Alerts[i].TimeStamp);
        $('#' + data.Alerts[i].Number + ' .alert-title').text(data.Alerts[i].AlertTitle);
        $('#' + data.Alerts[i].Number + ' .alert-status').text(data.Alerts[i].Status);
        $('#' + data.Alerts[i].Number + ' .alert-location').text(data.Alerts[i].Location);
        $('#' + data.Alerts[i].Number + ' .alert-event').text(data.Alerts[i].Message);

        for (var y = 0; y < data.Alerts[i].OIDs.length; y++) {
            var mapslatlng = new google.maps.LatLng(data.Alerts[i].OIDs[y].Lat, data.Alerts[i].OIDs[y].Long);
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
            bounds.extend(mapslatlng);

            if (oidString == '') {
                oidString = data.Alerts[i].OIDs[y].OID;
            } else {
                oidString = oidString + ', ' + data.Alerts[i].OIDs[y].OID;
            }
        }

<<<<<<< HEAD
        $('#alert-' + alertNum + ' .OID').text(oidString); 
        $('#alert-' + alertNum).css('visibility', 'visible');
=======
        $('#' + data.Alerts[i].Number + ' .OID').text(oidString);
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    }
}

function parseAreas(response) {
    var data = response;

<<<<<<< HEAD
    for(var k = 0; k < data.Areas.length; k++) {
        for(var i = 0; i < data.Areas[0].Zones.length; i++) {
=======
    for (var k = 0; k < data.Areas.length; k++) {
        for (var i = 0; i < data.Areas[0].Zones.length; i++) {
            console.log(data.Areas[0].Zones[i]);
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
            areaList.createNew(data.Areas[0].Zones[i], data.Areas[0].OID);
            setAreaOnMap(areaList.getArea(data.Areas[0].Zones[i].UID));
        }
    }

}

function parseLocations(response) {
    var data = response;

    for (var i = 0; i < data.Locations.length; i++) {

        var offenderMarker = markerList.getMarker(data.Locations[i].OID);

        if (offenderMarker != undefined) {
            offenderMarker.setPosition(new google.maps.LatLng(data.Locations[i].Lat, data.Locations[i].Lon));
        } else {
            console.log('marker not found');
        }
    }


}

//
//
// end message parsers

// adjusts the bounds to fit the selected alert.
function alertTitleHyperlink(element) {
    var alertId = alertList.getAlert($(element.parentNode.parentNode).attr('id'));
    var alertBounds = new google.maps.LatLngBounds();

    if (alertId != undefined) {
        for (var i = 0; i < alertId.OIDs.length; i++) {
            var alertlatlng = new google.maps.LatLng(alertId.OIDs[i].Lat, alertId.OIDs[i].Long);
            alertBounds.extend(alertlatlng);
        }

        map.fitBounds(alertBounds);
<<<<<<< HEAD
        map.setZoom(15);  
=======
        map.setZoom(15);
        console.log($(element.parentNode.parentNode).attr('id'));
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    }

}


function setUserLocation(OID, lat, lng) {
    var myLatlng = new google.maps.LatLng(lat, lng);

    var marker = markerList.getMarker(OID);

    if(marker != undefined) {
        marker.setPosition(myLatlng);
    } else {
        marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            icon: 'http://maps.google.com/mapfiles/kml/pal4/icon49.png',
            title: 'OID: ' + OID
        });
    }

    markerList.add(marker, OID);
    maintainBounds(myLatlng);

    // zoom on area
<<<<<<< HEAD
    //map.fitBounds(bounds);    
=======
    map.fitBounds(bounds);
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
}

function setAreaOnMap(area) {
    console.log('setAreaOnMap...');

    var areaCoordinates = [];

    for (var i = 0; i < area[1].Coordinates.length; i++) {
        areaCoordinates.push(new google.maps.LatLng(area[1].Coordinates[i].Lat, area[1].Coordinates[i].Lon));

    }

    anArea = new google.maps.Polygon({
        paths: areaCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35
    });

    anArea.setMap(map);
}

function maintainBounds(mapslatlng) { 
    bounds.extend(mapslatlng);
}

function connection() {
    console.log("WebSockets supported by browser...");

    var uri = wsUri;
    if (uri.indexOf("?") == -1) {
        uri += "?encoding=text";
    } else {
        uri += "&encoding=text";
    }

    ws = new WebSocket(uri);

    // define onopen
    ws.onopen = function (evt) { onOpen(evt) };

    // define onmessage
    ws.onmessage = function (evt) { onMessage(evt) };

    // define onclose
    ws.onclose = function (evt) { onClose(evt) };

    ws.onerror = function (evt) { onError(evt) };
}

function onOpen(evt) {
    console.log('onOpen...');
}

function onClose(evt) {
    console.log('onClose...');
    ws.close();
}

function onMessage(evt) {
    //$('.alert2345 .timestamp').text(evt.data);    
    onMessageHandler(evt.data);
    console.log('onMessage... ');
    console.log(evt.data);
        console.log('');
}

function onError(evt) {
    console.log('onError...');
}

/*
/*
/* Stringify JSON string to pass as a test */
<<<<<<< HEAD
function initTest() {  
=======
function initTest() {
    //console.log('Parsing test alert...');
    //parseAlerts(testAlert());    
    //console.log(' ');

    //console.log('Displaying offender locations...');
    //for(var i = 0; i < tracerContainer.getLength(); i++) {
    //console.log(offenderList);
    //var obje = tracerContainer.getOffender(i);
    //setUserLocation(obje.OID, obje.latitude, obje.longitude);   
    //}
    //console.log(' ');    

>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
    console.log('onMessageHandler Offender Message test...');
    onMessageHandler(testJSON());
    console.log(' ');

    console.log('onMessageHandler Alert Message test...');
    onMessageHandler(testAlert());
    console.log(' ');

    console.log('onMessageHandler Area Message test...');
    onMessageHandler(testArea());
    console.log(' ');

    console.log('onMessageHandler Location Message test...');
    setTimeout(function () {
        onMessageHandler(testLocations());
    }, 2000);

    console.log(' ');
}

function testJSON() {
    var obj = '{Offenders:[{OID:123456}]}';
    var anObj = '{"Offenders":[{"Offender":[{"OID":"30"},{"Locations":[{"TimeStamp":"1368765098","Lat":"47.609722","Lon":"-122.333056"},{"TimeStamp":"1368765994","Lat":"47.609722","Lon":"-122.333056"}]}]},{"Offender":[{"OID":"1234568"},{"Locations":[{"TimeStamp":"1368765098","Lat":"47.609953","Lon":"-122.336712"},{"TimeStamp":"1368765994","Lat":"47.609722","Lon":"-122.333056"}]}]}]}';
    var json = JSON.stringify(obj);

    return anObj;
}

function testAlert() {
    var anObj = '{"Alerts":[{"Number":"000001","TimeStamp":"1368765098","AlertTitle":"Crossed Over the Boundary","Message":"OID did what?!","Status":"pending","Event":"evt","Location":"Safeway","OIDs":[{"OID":"123456","Lat":"47.609722","Lon":"-122.333056","Bearing":""},{"OID":"1234568","Lat":"47.609953","Lon":"-122.336712","Bearing":""}]}]}';
    return anObj;
}

function testArea() {
    var anObj = '{"Areas":[{"OID":"123456","Zones":[{"UID":"061561303","Name":"Safeway","Coordinates":[{"Lat":"47.610287","Lon":"-122.342817"},{"Lat":"47.608394","Lon":"-122.343299"},{"Lat":"47.608596","Lon":"-122.339351"}]},{"UID":"5641329","Name":"Target","Coordinates":[{"Lat":"47.607555","Lon":"-122.333601"},{"Lat":"47.605645","Lon":"-122.336304"},{"Lat":"47.604893","Lon":"-122.333643"}]}]}]}';
    return anObj;
}

function testLocations() {
    var anObj = '{"Locations":[{"OID":"123456","Lat":"47.605847","Lon":"-122.325189","TimeStamp":"1368765098","Type":"Offender"},{"OID":"1234568","Lat":"47.607005","Lon":"-122.319481","TimeStamp":"1368765994","Type":"Offender"}]}';
    return anObj;
}
/*
/*
<<<<<<< HEAD
/* End test */ 

=======
/* End test */
>>>>>>> fdb82c1264882e9ce11c605e5d732d157d4b26ea
